package org.csu.mypetstore.controller;

import org.csu.mypetstore.domain.Category;
import org.csu.mypetstore.domain.Item;
import org.csu.mypetstore.domain.Product;
import org.csu.mypetstore.service.CatalogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/catalog")
public class CatalogController
{
    @Autowired
    private CatalogService catalogService;

    @GetMapping("/main")
    public String viewMain()
    {
        return "catalog/main";
    }

    @GetMapping("/category")
    public String viewCategory(@RequestParam("categoryId") String categoryId, Model model)
    {
        if (categoryId != null)
        {
            Category category = catalogService.getCategory(categoryId);
            List<Product> productList = catalogService.getProductListByCategory(categoryId);
            model.addAttribute("category", category);
            model.addAttribute("productList", productList);
        }
        return "catalog/category";
    }

    @GetMapping("/product")
    public String viewProduct(@RequestParam("productId") String productId, Model model)
    {
        if (productId != null)
        {
            Product product = catalogService.getProduct(productId);
            List<Item> itemList = catalogService.getItemListByProduct(productId);
            model.addAttribute("product", product);
            model.addAttribute("itemList", itemList);
        }
        return "catalog/product";
    }

    @GetMapping("/item")
    public String viewItem(@RequestParam("itemId") String itemId, Model model)
    {
        if (itemId != null)
        {
            Item item = catalogService.getItem(itemId);
            Product product = catalogService.getProduct(item.getProductId());
            model.addAttribute("item", item);
            model.addAttribute("product", product);
        }
        return "catalog/item";
    }

    @PostMapping("/search")
    public String search(@RequestParam("keyword") String keyword, Model model)
    {
        List<Product> productList = catalogService.searchProductList(keyword);
        model.addAttribute("productList", productList);
        return "catalog/search";
    }

    @GetMapping("/searchAjax")
    @ResponseBody
    public List<Product> searchAjax(@RequestParam("keyword") String keyword)
    {
        return catalogService.searchProductList(keyword);
    }
}
